<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { useViewStore } from "../../store/index";
import { storeToRefs } from "pinia";
import { goBack, goPage } from "../../utils/index";
import type { Good, GoodFilter } from "../../types/good";
import { getGoodsList } from "../../service/goods";
import { BASE_URL } from "../../service/index";
import { formatPrice } from "../../utils";

const { buttonRectInfo } = storeToRefs(useViewStore());
const keyword = ref("");
const loading = ref(false);
// 搜索历史记录
const searchHistory = ref<string[]>([]);
// 搜索结果
const searchResults = ref<Good[]>([]);
// 是否已经搜索过
const hasSearched = ref(false);
const focusFlag = ref(true);

// 执行搜索操作
const search = async () => {
  if (!keyword.value.trim()) {
    uni.showToast({
      title: "请输入搜索关键词",
      icon: "none",
    });
    return;
  }

  loading.value = true;
  hasSearched.value = true;

  try {
    // 构建搜索参数
    const params: GoodFilter = {
      name: keyword.value.trim(),
      page: 1,
      pageSize: 20,
    };

    // 调用API获取搜索结果
    const result = await getGoodsList(params);
    searchResults.value = result.list || [];

    // 保存到搜索历史
    saveToHistory(keyword.value.trim());

    if (searchResults.value.length === 0) {
      uni.showToast({
        title: "未找到相关产品",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("搜索失败:", error);
    uni.showToast({
      title: "搜索失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 使用历史记录进行搜索
const searchWithHistory = (item: string) => {
  keyword.value = item;
  search();
};

// 保存搜索关键词到历史记录
const saveToHistory = (key: string) => {
  // 如果已存在则移除旧的
  const index = searchHistory.value.indexOf(key);
  if (index > -1) {
    searchHistory.value.splice(index, 1);
  }

  // 添加到头部
  searchHistory.value.unshift(key);

  // 限制历史记录数量为10条
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10);
  }

  // 保存到本地存储
  uni.setStorageSync("searchHistory", JSON.stringify(searchHistory.value));
};

// 清空历史记录
const clearHistory = () => {
  searchHistory.value = [];
  uni.removeStorageSync("searchHistory");
  uni.showToast({
    title: "历史记录已清空",
    icon: "success",
    duration: 1500,
  });
};

// 查看产品详情
const viewProductDetail = (product: Good) => {
  goPage(`/pages/detail/index?id=${product.id}`);
};

// 监听搜索框回车事件
const onSearchConfirm = () => {
  search();
};

// 加载本地存储的历史记录
const loadHistory = () => {
  try {
    const storedHistory = uni.getStorageSync("searchHistory");
    if (storedHistory) {
      searchHistory.value = JSON.parse(storedHistory);
    }
  } catch (error) {
    console.error("加载搜索历史失败:", error);
  }
};

// 在组件挂载时加载历史记录
onMounted(() => {
  loadHistory();
});
</script>

<template>
  <view class="status_bar" :style="{
    height: `${buttonRectInfo.top - 6}px`,
  }">
    <!-- 这里是状态栏 -->
  </view>
  <view class="search-page page-warpper" :style="{ height: `calc( 100vh - ${buttonRectInfo.top}px )` }">
    <!-- 搜索头部，固定不动 -->
    <wd-navbar>
      <template #left>
        <view class="search-box">
          <wd-icon name="thin-arrow-left" size="36rpx" @click="goBack"></wd-icon>
          <view style="flex: 1">
            <wd-search v-model="keyword" hide-cancel placeholder-left placeholder="搜索您的心仪产品" :focus="focusFlag"
              @search="onSearchConfirm"></wd-search>
          </view>
        </view>
      </template>
    </wd-navbar>

    <!-- 搜索历史区域 - 固定不动 -->
    <view class="search-section history-section">
      <view class="section-header">
        <text class="section-title">搜索历史</text>
        <view class="clear-history" @click="clearHistory" v-if="searchHistory.length > 0">
          <wd-icon name="delete" size="40rpx" color="#808080"></wd-icon>
        </view>
      </view>

      <!-- 有搜索历史时显示标签 -->
      <view class="history-tags" v-if="searchHistory.length > 0">
        <view class="history-tag" v-for="(item, index) in searchHistory" :key="index" @click="searchWithHistory(item)">
          {{ item }}
        </view>
      </view>

      <!-- 无搜索历史时显示提示 -->
      <view class="empty-history" v-else>
        <wd-text text="暂无搜索历史"></wd-text>
      </view>
    </view>

    <!-- 搜索结果容器 -->
    <view class="result-container">
      <!-- 搜索结果区域标题 - 固定不动 -->
      <view class="result-header">
        <text class="section-title">搜索结果</text>
        <text class="result-count" v-if="hasSearched && searchResults.length > 0">
          共 {{ searchResults.length }} 件产品
        </text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-container" v-if="loading">
        <wd-loading type="outline" color="#242424"></wd-loading>
      </view>

      <!-- 搜索结果内容区 - 可滚动 -->
      <scroll-view scroll-y class="result-scroll" v-else>
        <!-- 未开始搜索时的提示 -->
        <view class="empty-result" v-if="!hasSearched">
          <wd-status-tip image="search" tip="输入关键词开始搜索"></wd-status-tip>
        </view>

        <!-- 有搜索结果时显示产品列表 -->
        <view class="product-list" v-else-if="searchResults.length > 0">
          <view class="product-item" v-for="product in searchResults" :key="product.id"
            @click="viewProductDetail(product)">
            <view class="product-image" :style="{
              backgroundImage: `url(${BASE_URL}/api/file/${product.img})`,
            }"></view>
            <view class="product-info">
              <view class="product-name">{{ product.name }}</view>
              <view class="price-container">
                <text class="price-symbol">¥</text>
                <text class="price-integer">{{
                  formatPrice(product.price).integer
                }}</text>
                <text class="price-decimal">.{{ formatPrice(product.price).decimal }}</text>
              </view>
              <view class="product-type">{{ product.type }}</view>
            </view>
          </view>
        </view>

        <!-- 搜索后无结果时显示提示 -->
        <view class="empty-result" v-else-if="hasSearched">
          <wd-status-tip image="search" tip="未找到相关产品，换个关键词试试吧"></wd-status-tip>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.search-page {
  --columns: 2;
  /* 默认两列 */
  --gap: 20rpx;

  @media screen and (max-width: 320px) {
    --columns: 1;
    /* 小屏一列 */
  }

  @media screen and (min-width: 768px) {
    --columns: 3;
    /* 大屏三列 */
  }

  & {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background-color: #fff;
  }

  .search-box {
    display: flex;
    height: 100%;
    width: 100%;
    margin-left: -30rpx;
    padding-left: 24rpx;
    align-items: center;
    gap: 24rpx;
  }

  .search-section {
    padding: 30rpx;
    background-color: #fff;
    margin: 20rpx;
    border-radius: var(--border-radius);
  }

  .history-section {
    flex-shrink: 0;
    /* 防止历史区域被压缩 */

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .section-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .clear-history {
        padding: 10rpx;
      }
    }

    .history-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;

      .history-tag {
        padding: 12rpx 24rpx;
        background-color: #f5f5f5;
        border-radius: var(--border-radius);
        font-size: 28rpx;
        color: #666;
      }
    }

    .empty-history {
      padding: 20rpx 0;
      display: flex;
      justify-content: center;
    }
  }

  .result-container {
    flex: 1;
    /* 占据剩余空间 */
    display: flex;
    flex-direction: column;
    margin: 0 20rpx 20rpx;
    background-color: #fff;
    border-radius: var(--border-radius);
    overflow: hidden;

    .result-header {
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;

      .section-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .result-count {
        font-size: 24rpx;
        color: #999;
      }
    }

    .loading-container {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .result-scroll {
      flex: 1;
      /* 占满剩余空间 */
      height: 0;
      /* 必须为0，让flex属性生效 */
    }

    .empty-result {
      padding: 60rpx 0;
      display: flex;
      justify-content: center;
    }

    .product-list {
      padding: 20rpx 0;
      display: flex;
      flex-wrap: wrap;
      gap: var(--gap);

      .product-item {
        display: flex;
        padding: 12rpx;
        background-color: #fff;
        border: 1px solid #f4f4f4;
        border-radius: var(--border-radius);
        width: calc((100% - (var(--columns) - 1) * var(--gap)) / var(--columns));
        box-sizing: border-box;
        overflow: hidden;

        .product-image {
          width: 160rpx;
          height: 160rpx;
          background-size: cover;
          background-position: center;
          border-radius: var(--border-radius);
          margin-right: 10rpx;
          flex-shrink: 0;
        }

        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          max-width: 50%;

          .product-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            overflow: hidden;
            width: 100%;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .product-price {
            font-size: 32rpx;
            font-weight: 700;
            color: #4e5a37;
          }

          .product-type {
            font-size: 24rpx;
            color: #666;
            padding: 4rpx 12rpx;
            background-color: #f5f5f5;
            border-radius: 4rpx;
            display: inline-block;
            width: fit-content;
          }
        }
      }
    }
  }
}
</style>
